﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;

namespace Extensions.Services;

/// <summary>
/// 大数字序列化器  针对long类型序列化的时候  会丢失精度  所有重新了long类型的转换
/// </summary>
public class JsonNumberConverter : JsonConverter
{
    private readonly Type[] _types;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="types"></param>
    public JsonNumberConverter(params Type[] types)
    {
        this._types = types;
    }

    /// <inheritdoc />
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JToken t = JToken.FromObject(value);

        if (t.Type == JTokenType.Integer)
        {
            writer.WriteValue(value.ToString());
        }
        else
        {
            t.WriteTo(writer);
        }
    }

    /// <inheritdoc />
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanRead is false.The type will skip the converter.");
    }

    /// <inheritdoc />
    public override bool CanRead => false;

    /// <inheritdoc />
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(long) || objectType == typeof(decimal);
    }
}